<!-- 个税记录编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="470"
    :model-value="modelValue"
    :title="isUpdate ? '修改个税记录' : '添加个税记录'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="月份" prop="belongs_month">
        <el-date-picker
          v-model="form.belongs_month"
          type="month"
          placeholder="选择月份"
          style="width: 150px"
          value-format="YYYY-MM"
        />
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input
          v-model="form.amount"
          @input="handleInput"
          style="width: 150px"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { updateMemberTax } from '@/api/company';

  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    studentId: Number
  });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    member_id: '',
    belongs_month: '',
    amount: ''
  });

  /** 表单验证规则 */
  const rules = reactive({
    belongs_month: [
      {
        required: true,
        message: '请选择个税月份',
        type: 'string',
        trigger: 'blur'
      }
    ],
    amount: [
      {
        required: true,
        message: '请输入个税金额',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });
  const handleInput = () => {
    let value = form.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    form.amount = value;
  };

  /** 保存编辑 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      var requestData = Object.assign({}, form);
      requestData.student_id = props.studentId;
      updateMemberTax(requestData)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.data) {
          assignFields(props.data);
          isUpdate.value = true;
        } else {
          form.member_id = props.studentId;
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
